package com.buss.auth.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.buss.auth.transfer.vo.authen.AuthUserVO;
import com.buss.member.entity.FunctionEntity;
import com.buss.member.entity.GeneralUserEntity;
import com.buss.member.entity.RoleAndFunctionEntity;
import com.buss.member.entity.RoleEntity;
import com.buss.member.entity.UserAndRoleEntity;

import com.buss.common.service.SysServiceI;

@Service("monitorRealm")
public class MonitorRealm extends AuthorizingRealm {
	/*
	 * @Autowired UserService userService;
	 * 
	 * @Autowired RoleService roleService;
	 * 
	 * @Autowired LoginLogService loginLogService;
	 */
	@Autowired
	private SysServiceI sysService;

	public MonitorRealm() {
		super();

	}

	/**
	 * 获取授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		/* 这里编写授权代码 */
		Set<String> roleNames = new HashSet<String>();
	    Set<String> permissions = new HashSet<String>();
	    
	    Subject currentUser = SecurityUtils.getSubject();
	    AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
	    GeneralUserEntity userEntity = this.sysService.get(GeneralUserEntity.class, user.getId());
	    if(userEntity != null){
	    	List<UserAndRoleEntity> userAndRoleList = userEntity.getRoles();
		    for(UserAndRoleEntity ur : userAndRoleList){
		    	RoleEntity role = ur.getRole();
		    	roleNames.add(role.getCode());
		    	List<RoleAndFunctionEntity> roleAndFunList = role.getFunctions();
		    	for(RoleAndFunctionEntity rf : roleAndFunList){
		    		FunctionEntity fun = rf.getFunction();
		    		permissions.add(fun.getValue());
		    	}
		    }
	    } else {
//	    	HXUser tsuser = this.sysService.get(HXUser.class, user.getId());
//	    	List<TSRoleUser> ruList = sysService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
//	    	for(TSRoleUser ru : ruList){
//	    		TSRole role = ru.getTSRole();
//	    		roleNames.add(role.getRoleCode());
//	    	}
	    }
	    
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
	    info.setStringPermissions(permissions);
		return info;

	}

	/**
	 * 获取身份验证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		/* 这里编写认证代码 */
		GeneralUserEntity userExample = new GeneralUserEntity();
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//		User user = securityApplication.findby(upToken.getUsername());
		userExample.setMphone(token.getUsername());
		
		String username = "";
		String password = "";
		// 查用户邮箱
//		GeneralUserEntity user = (GeneralUserEntity)sysService.findUniqueByProperty(GeneralUserEntity.class, 
//				"email", token.getUsername());
		
//		String hql = "from GeneralUserEntity where email=? and checkstatus>9";
//		GeneralUserEntity user = (GeneralUserEntity)sysService.findHql(hql, token.getUsername()).get(0);
		
		String hql = "from GeneralUserEntity where email='"+token.getUsername()+"' and checkstatus>9";
		GeneralUserEntity user = (GeneralUserEntity)sysService.singleResult(hql);
		if (user != null) {
			username = user.getEmail();
			password = user.getPwd();
		} 
		else if ("".equals(username)) {
			// 查用户手机号
//			user = (GeneralUserEntity)sysService.findUniqueByProperty(GeneralUserEntity.class, 
//					"mphone", token.getUsername());
//			String hql2 = "from GeneralUserEntity where mphone=? and checkstatus>9";
//			user = (GeneralUserEntity)sysService.findHql(hql2, token.getUsername()).get(0);
			String hql2 = "from GeneralUserEntity where mphone='"+token.getUsername()+"' and checkstatus>9";
			user = (GeneralUserEntity)sysService.singleResult(hql2);
			if (user != null) {
				username = user.getMphone();
				password = user.getPwd();
			} else{
				return null;
			}
		}
		else {
			//如果前端表中不存在用户，就从后端表中查询
//			HXUser tsuser = sysService.findUniqueByProperty(HXUser.class, "mphone", token.getUsername());
//			if(tsuser != null){
//				return new SimpleAuthenticationInfo(tsuser.getMphone(),tsuser.getPwd(), getName());
//			} else {
//				throw new AuthenticationException();
//			}
		}
		
		return new SimpleAuthenticationInfo(username,password, getName());
	}

	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}


}
